package threadlocal_test;

import org.junit.Test;

import java.text.SimpleDateFormat;
import java.util.HashSet;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author Ajie
 * @date 2020-05-28
 * @function
 *
 * 参考：https://blog.csdn.net/Lammonpeter/article/details/105175187
 */
public class ThreadLocal_Random {

    private static final org.apache.log4j.Logger logger =org.apache.log4j.Logger.getLogger(ThreadLocal_Random.class);

    private ExecutorService pool= Executors.newFixedThreadPool(10);
    private static HashSet<Random>  set = new HashSet<>();

    private ThreadLocal<Student> studentThreadLocal = new ThreadLocal<>();


    public static void main(String[] args) {
        for (int i = 0; i < 100; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Random random = randomThreadLocal.get();
                    set.add(random);
                    logger.info("run: size "+set.size());
                }
            }).start();
        }
    }

    @Test
    public void testThreadLocal(){
        Student student = new Student();
        student.name = "lemon";
        student.sex = "female";
        student.score = "99";
        studentThreadLocal.set(student);

        Student student1 = studentThreadLocal.get();
        logger.info("testThreadLocal: "+student1);
        for (int i = 0; i < 100; i++) {
            pool.submit(new Runnable() {
                @Override
                public void run() {

                    Student student1 = studentThreadLocal.get();
                    logger.info("testThreadLocal: "+student1);
                }
            });

        }
    }

    @Test
    public void testPoolThreadLocalInstance(){
        for (int i = 0; i < 100; i++) {
            pool.submit(new Runnable() {
                @Override
                public void run() {
                    Random random = randomThreadLocal.get();
                    set.add(random);
                    logger.info("run: "+set.size());
                }
            });
        }

        // 关闭线程池，此种关闭方式不再接受新的任务提交，等待现有队列中的任务全部执行完毕之后关闭
        pool.shutdown();
    }



    static volatile int newCount = 0;
    static ThreadLocal<Random> randomThreadLocal = new ThreadLocal<Random>(){
        @Override
        protected Random initialValue() {

            Random random = new Random();
            return random;
        }
    };


    class Student {

        /**
         * 姓名、性别、成绩
         */
        String name;
        String sex;
        String score;

    }
}

class ThreadSafeDateFormatter {

    public static ThreadLocal<SimpleDateFormat> dateFormatThreadLocal = new ThreadLocal<SimpleDateFormat>() {
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        }
    };
}
